package net.oschina.app.viewpagerfragment.eventsdetailfragment;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.jcodecraeer.xrecyclerview.XRecyclerView;

import net.oschina.app.MApp;
import net.oschina.app.R;
import net.oschina.app.adapter.MyEventsAdapter;
import net.oschina.app.bean.Event;
import net.oschina.app.bean.EventList;
import net.oschina.app.interf.OnRecycleViewItemClickListener;
import net.oschina.app.ui.EventsWebViewActivity;
import net.oschina.app.util.MyHttpUtils;
import net.oschina.app.util.PreferencesUtils;
import net.oschina.app.util.XmlUtils;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by huang on 2017-4-2.
 * 我的活动
 */

public class MyEventsFragment extends Fragment{
    private List<Event> mList = new ArrayList<>();//bean类集合
    private XRecyclerView mRecyclerView;
    private MyEventsAdapter mMyEventsAdapter;
    private int page = 0;//初始接口页
    private View mFooterView;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mRecyclerView = (XRecyclerView) inflater.inflate(R.layout.events_fragment,container,false);
        initView();
        initData();
        initEvent();
        return mRecyclerView;
    }

    //初始化视图
    private void initView() {
        //页脚
        mFooterView = View.inflate(getContext(), R.layout.xrecyclerview_footer,null);
        LinearLayoutManager manager = new LinearLayoutManager(getContext());
        mRecyclerView.setLayoutManager(manager);
        mRecyclerView.setFootView(mFooterView);//添加脚布局
    }

    //获取数据
    private void initData() {
        String url = "http://10.0.2.2:8080/oschina/list/my_event_list/page"+ page +".xml";
        MyHttpUtils myHttpUtils = new MyHttpUtils();
        myHttpUtils.getDate(url, EventList.class, new MyHttpUtils.OngetDatesResult() {
            @Override
            public void Onsucessful(Object bean) {
                EventList eventList = (EventList) bean;
                mList = eventList.getList();
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mMyEventsAdapter = new MyEventsAdapter(getContext(), mList);
                        mRecyclerView.setAdapter(mMyEventsAdapter);//更新UI

                        //监听条目点击事件
                        initItemClick();
                    }
                });
            }
            @Override
            public void Onfail() {

            }
        });

    }

    //初始化事件
    private void initEvent() {
        mRecyclerView.setPullRefreshEnabled(true);//开启刷新
        mRecyclerView.setLoadingMoreEnabled(true);//开启加载更多
        mRecyclerView.setLoadingListener(new XRecyclerView.LoadingListener() {
            //下拉刷新
            @Override
            public void onRefresh() {
                MApp.mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(MApp.mContext, "刷新成功", Toast.LENGTH_SHORT).show();
                        mRecyclerView.refreshComplete();
                    }
                },1000);
            }

            @Override
            public void onLoadMore() {
                OkHttpClient client = new OkHttpClient();
                String url = "http://10.0.2.2:8080/oschina/list/my_event_list/page"+ page +".xml";
                Request.Builder builder = new Request.Builder().url(url);
                Request request = builder.build();
                Call call = client.newCall(request);
                call.enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        Log.d("MyEventsFragment", "e:" + e.getMessage());
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        InputStream inputStream = response.body().byteStream();
                        EventList eventBean = XmlUtils.toBean(EventList.class, inputStream);
                        if(eventBean!= null) {
                            page++;
                            mList.addAll(eventBean.getList());
                            getActivity().runOnUiThread(new Runnable() {//跑在主线程
                                @Override
                                public void run() {
                                    mMyEventsAdapter.notifyDataSetChanged();//通知数据更新
                                    mRecyclerView.loadMoreComplete();
                                }
                            });
                        } else {
                            getActivity().runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    mRecyclerView.setNoMore(true);
                                }
                            });

                        }
                    }
                });
            }
        });
    }
    //初始化条目点击事件
    private void initItemClick() {
        if(mMyEventsAdapter != null) {
            //设置条目点击监听
            mMyEventsAdapter.setOnItemClickListener(new OnRecycleViewItemClickListener() {
                @Override
                public void onClick(View view, int position) {
                    position = position - 1;
                    Event event = mList.get(position);

                    //保存条目点击状态
                    int id = event.getId();
                    String ids = PreferencesUtils.getString(MApp.mContext, "meItem_isRead", "");
                    if(!ids.contains(id+"")) {
                        ids += id;
                        PreferencesUtils.putString(MApp.mContext,"meItem_isRead",ids);
                    }
                    TextView tvEventTitle = (TextView) view.findViewById(R.id.tv_events_title);
                    tvEventTitle.setTextColor(Color.parseColor("#9C9A9C"));

                    //跳转到webView页面
                    Intent intent = new Intent(getContext(), EventsWebViewActivity.class);
                    String url1 = event.getUrl();
                    intent.putExtra("url",url1);
                    startActivity(intent);


                }
            });
        }
    }
}
